//
//  HNSH_OrderListViewController.m
//  HNSH_SingleProject
//
//  Created by 李宇廷 on 2023/3/1.
//

#import "HNSH_OrderListViewController.h"

//view
#import "HNSH_OrderListCell.h"
#import "HNSH_OrderListFooter.h"
#import "HNSH_OrderListHeader.h"

//vc
#import "HNSH_OrderDetailViewController.h"                  //订单详情
#import "HNSH_LogisticsViewController.h"                    //物流
#import "HNSH_CashierPayViewController.h"                   //收银台
#import "HNSH_ConfirmOrderViewController.h"                 //确认订单
#import "HNSH_RefundApplyViewController.h"                  //售后申请
#import "HNSH_RefundDetailViewController.h"                 //售后详情

@interface HNSH_OrderListViewController ()

/* listAry */
@property (nonatomic, strong) NSMutableArray *listAry;

@end

static NSString *HNSH_OrderListCellID = @"HNSH_OrderListCellID";
static NSString *HNSH_OrderListFooterID = @"HNSH_OrderListFooterID";
static NSString *HNSH_OrderListHeaderID = @"HNSH_OrderListHeaderID";

@implementation HNSH_OrderListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self configTableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refrashListView) name:@"KOrderListRefrash" object:nil];
}

- (void)refrashListView {
    [self headerRefreshing];
}

//MARK: 点击按钮
- (void)clickBtnWithBtn:(UIButton *)sender model:(HNSH_OrderListModel *)model {
    if ([sender.currentTitle isEqualToString:@"确认收货"]) {
        //确认收货
        [self showViewWithText:@"是否确认收货？" model:model type:2];
    }
    if ([sender.currentTitle isEqualToString:@"取消订单"]) {
        //取消订单
        [self showViewWithText:@"是否取消该订单？" model:model type:3];
    }
    if ([sender.currentTitle isEqualToString:@"删除订单"]) {
        //删除订单
        [self showViewWithText:@"是否删除该订单？" model:model type:4];
    }
    if ([sender.currentTitle isEqualToString:@"再次购买"]) {
        //再次购买
        [self buyAgainWithModel:model];
    }
    if ([sender.currentTitle isEqualToString:@"查看物流"]) {
        //查看物流
        if (![model.shipping_code isNotBlank]) {
            [self.view makeToast:@"暂无物流信息，不能查看物流"];
            return;
        }
        HNSH_LogisticsViewController * vc = [HNSH_LogisticsViewController new];
        vc.orderModel = model;
        [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
    }
    if ([sender.currentTitle isEqualToString:@"立即付款"]) {
        //立即付款
        [self payWithModel:model];
    }
    if ([sender.currentTitle isEqualToString:@"申请售后"]) {
        HNSH_RefundApplyViewController * vc = [HNSH_RefundApplyViewController new];
        vc.orderId = model.uid;
        [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
    }
    if ([sender.currentTitle isEqualToString:@"售后详情"]) {
        HNSH_RefundDetailViewController * vc = [HNSH_RefundDetailViewController new];
        vc.orderId = model.uid;
        [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
    }
}

//MARK: 展示弹框
- (void)showViewWithText:(NSString *)text model:(HNSH_OrderListModel *)model type:(NSInteger)type{
    WeakSelf(weakSelf);
    [HNSH_AlertView showTitle:text des:@"" buttonTitle:@"确定" buttonColor:[UIColor appGreenColor] buttonClick:^{
        [weakSelf changeStatusWithModel:model type:type];
    }];
}

//MARK: 修改订单状态
- (void)changeStatusWithModel:(HNSH_OrderListModel *)model type:(NSInteger)type{
    if (type == 4) {
        //删除订单
        [self deleteOrderWithModel:model];
    } else if (type == 3) {
        //取消订单
        [self cancelOrderWithModel:model];
    } else if (type == 2) {
        //确认收货
        [self completeOrderWithModel:model];
    }
}

//MARK: 再次购买
- (void)buyAgainWithModel:(HNSH_OrderListModel *)model {
    HNSH_ConfirmOrderGoodsModel *specModel = model.items[0];
    HNSH_ConfirmOrderViewController * vc = [HNSH_ConfirmOrderViewController new];
    vc.goods_id = specModel.goods_id;
    vc.spec_id = specModel.spec_id;
    vc.quantity = [specModel.quantity integerValue];
    vc.payment_type = model.payment_type;
    [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
}

- (void)pushVCWithModel:(HNSH_CashierPayModel *)model{
    HNSH_CashierPayViewController * vc = [HNSH_CashierPayViewController new];
    vc.payModel = model;
    [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
}

#pragma mark networking
//MARK: 订单列表
- (void)refreshData:(NSInteger)page {
    [HNSH_ShopNetServer requestGoodsOrderListWithStatus:self.parameter page_num:page success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            if (page == 1) {
                [self.listAry removeAllObjects];
            }
            NSArray * list = responseObject.resultset[@"list"];
            NSArray * array = [NSArray yy_modelArrayWithClass:HNSH_OrderListModel.class json:list];
            [self.listAry addObjectsFromArray:array];
            [self endRefresh:array.count>=10];
            [self.tableView reloadData];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 删除订单
- (void)deleteOrderWithModel:(HNSH_OrderListModel *)model{
    [HNSH_ShopNetServer requestGoodsOrderRemoveWithOrderId:model.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self headerRefreshing];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 取消订单
- (void)cancelOrderWithModel:(HNSH_OrderListModel *)model{
    [HNSH_ShopNetServer requestGoodsOrderCancelWithOrderId:model.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self headerRefreshing];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}

//MARK: 确认收货
- (void)completeOrderWithModel:(HNSH_OrderListModel *)model{
    [HNSH_ShopNetServer requestGoodsOrderCompleteWithOrderId:model.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            [self headerRefreshing];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}


//MARK: 立即付款
- (void)payWithModel:(HNSH_OrderListModel *)model{
    [HNSH_ShopNetServer requestGoodsOrderPaymentInfoWithOrderId:model.uid success:^(ST_BaseNetModel * _Nullable responseObject) {
        if (responseObject.code == 0) {
            NSDictionary * data = responseObject.resultset;
            HNSH_CashierPayModel * model = [HNSH_CashierPayModel yy_modelWithDictionary:data];
            [self pushVCWithModel:model];
        }
    } Failure:^(NSError * _Nullable error) {
        
    }];
}


#pragma mark lazy
- (NSMutableArray *)listAry {
    if (!_listAry) {
        _listAry = [NSMutableArray arrayWithCapacity:0];
    }
    return _listAry;
}

//MARK: 配置tableView
- (void)configTableView {
    [self setupRefresh:self.tableView option:ST_RefreshDefault];
    [self setupEmpty:self.tableView image:[UIImage imageNamed:@"empty_order"] title:@""];
    
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    self.tableView.rowHeight = 106;
    [self.tableView registerClass:[HNSH_OrderListCell class] forCellReuseIdentifier:HNSH_OrderListCellID];
    [self.tableView registerClass:[HNSH_OrderListHeader class] forHeaderFooterViewReuseIdentifier:HNSH_OrderListHeaderID];
    [self.tableView registerClass:[HNSH_OrderListFooter class] forHeaderFooterViewReuseIdentifier:HNSH_OrderListFooterID];
}

#pragma mark - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.listAry.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    HNSH_OrderListModel *model = self.listAry[section];
    return model.items.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 88.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 126.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    HNSH_OrderListFooter *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HNSH_OrderListFooterID];
    HNSH_OrderListModel *model = self.listAry[section];
    footer.model = model;
    WeakSelf(weakSelf);
    footer.buttonBlock = ^(UIButton * _Nonnull button, HNSH_OrderListModel * _Nonnull itemModel) {
        [weakSelf clickBtnWithBtn:button model:itemModel];
    };
    return footer;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    HNSH_OrderListHeader *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HNSH_OrderListHeaderID];
    HNSH_OrderListModel *model = self.listAry[section];
    header.model = model;
    return header;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 106;
}
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 106;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HNSH_OrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:HNSH_OrderListCellID];
    HNSH_OrderListModel *model = self.listAry[indexPath.section];
    cell.model = model.items[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HNSH_OrderDetailViewController *vc = [[HNSH_OrderDetailViewController alloc]init];
    vc.orderModel = self.listAry[indexPath.section];
    [[UIViewControllerHelper findCurrentShowingViewController].navigationController pushViewController:vc animated:YES];
}

@end
